﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
//using ThaireInvestmentWeb.BusinessDelegate;
using Thaire.Investment.Common;
using ThaireInvestmentWeb.Models;
using ThaireInvestmentWeb.Util;
using ThaireInvestmentWeb.WcfSerivce;

namespace ThaireInvestmentWeb.Controllers.Instrument
{
    public class UnitTrustController : Controller
    {
        private WcfSerivce.InvestmentServiceClient _service;
        public WcfSerivce.InvestmentServiceClient Service
        {
            get { return _service ?? (_service = ServiceFactory.GetService()); }
        }

        #region ManageUnitTrustHeader

        public ActionResult ManageUnitTrust()
        {
            ManageUnitTrustModel model = null;
            try
            {
                var data = Service.GetUnitTrustHeaderScreenData(null);
                model = ManageUnitTrustModel.BuildModel(data);
            }
            catch (Exception ex)
            {
                model = new ManageUnitTrustModel();
                //ModelState.AddModelError("", ex.Message);
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }
            TempData["ManageUnitTrustModel"] = model;
            return View("ManageUnitTrust", model);
        }

        [HttpPost]
        public ActionResult SearchUnitTrustHeader(ManageUnitTrustModel model)
        {
            var oldModel = (ManageUnitTrustModel)TempData["ManageUnitTrustModel"];

            try
            {
                if (!String.IsNullOrEmpty(model.SearchBtn))
                {
                    oldModel.Result = Service.SearchUnitTrust(model.SearchFilter);
                    if (oldModel.Result == null || oldModel.Result.Count == 0)
                    {
                        ViewBagUtil.SetDataNotFoundInfo(ViewBag);
                    }
                }
                else if (!String.IsNullOrEmpty(model.ResetBtn))
                {
                    ModelState.Clear();
                    oldModel.ClearFilterAndData();
                }
                TempData["ManageUnitTrustModel"] = oldModel;
            }
            catch (Exception ex)
            {
                //ViewData["error"] = ex.Message;
                // ModelState.AddModelError("", ex.Message);
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }
            //return View("fixedIncomeLIst", oldModel);
            return View("ManageUnitTrust", oldModel);
        }
        #endregion

        #region UnitTrustHeader
        public ActionResult GetMaturityStatus(DateTime? maturityDate, DateTime? issueDate)
        {
            var model = (EditUnitTrustHeaderModel)TempData["EditUnitTrustHeaderModel"];
            var issutTerm = WebUtil.NonApplicableIfZero(Calculator.CalFixIncomeIssueTerm(maturityDate, issueDate));
            TempData["EditUnitTrustHeaderModel"] = model;
            return Json(maturityDate.GetValueOrDefault().Date >= DateTime.Now.Date ? new { MaturityStatus = "Matured", IssuerTermDsp = issutTerm }
                : new { MaturityStatus = "Alive", IssuerTermDsp = issutTerm });
        }
        public ActionResult GetInvolvedType(int id)
        {
            var model = (EditUnitTrustHeaderModel)TempData["EditUnitTrustHeaderModel"];
            TempData["EditUnitTrustHeaderModel"] = model;
            var involve = model.ScreenData.InvolvedPartyTypes.SingleOrDefault(x => x.InvolvedPartyTypeId == id);
            return Json(involve != null ? new { InvolvedPartyTypeReference = involve.InvolvedPartyTypeReference, InvolvedPartyTypeCode = involve.InvolvedPartyTypeCode }
                : new { InvolvedPartyTypeReference = "", InvolvedPartyTypeCode = "" });
        }
        public ActionResult GetFundEnNameAutocomplete(string name)
        {
            var model = (EditUnitTrustHeaderModel)TempData["EditUnitTrustHeaderModel"];
            TempData["EditUnitTrustHeaderModel"] = model;
            var data = Service.GetFundEnNamesByName(name);
            var filteredItems = data.Select(o => o.Name).ToList();
            return Json(filteredItems, JsonRequestBehavior.AllowGet);

        }
        public ActionResult GetFundThNameAutocomplete(string name)
        {
            var model = (EditUnitTrustHeaderModel)TempData["EditUnitTrustHeaderModel"];
            TempData["EditUnitTrustHeaderModel"] = model;
            var data = Service.GetFundThNamesByName(name);
            var filteredItems = data.Select(o => o.Name).ToList();
            return Json(filteredItems, JsonRequestBehavior.AllowGet);
        }

        public ActionResult EditUnitTrustHeader(int? headerId)
        {
            EditUnitTrustHeaderModel model = null;
            try
            {
                var data = Service.GetUnitTrustHeaderScreenData(headerId);
                model = EditUnitTrustHeaderModel.BuildModel(data);
                if (data != null && data.HeaderDTO != null)
                {
                    model.UpdateMode = true;
                    ViewBag.UpdateMode = true;
                }
                TempData["EditUnitTrustHeaderModel"] = model;
            }
            catch (Exception ex)
            {
                model = new EditUnitTrustHeaderModel();
                //ModelState.AddModelError("", ex.Message);
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }
            return View(model);
        }
        [HttpPost]
        public ActionResult EditUnitTrustHeader(EditUnitTrustHeaderModel model)
        {
            var oldModel = (EditUnitTrustHeaderModel)TempData["EditUnitTrustHeaderModel"];
            if (ModelState.IsValid)
            {
                try
                {
                    if (!String.IsNullOrEmpty(model.SaveBtn))
                    {
                        var involvedPartyType = oldModel.InvolvedPartyTypeNameList.SingleOrDefault(x => x.Value == model.Header.InvolvedPartyTypeID.GetValueOrDefault().ToString());
                        if (involvedPartyType != null)
                            model.Header.InvolvedPartyTypeName = involvedPartyType.Text;
                        var unitTrustType = oldModel.TypeList.SingleOrDefault(x => x.Value == model.Header.UnitTrustTypeID.GetValueOrDefault().ToString());
                        if (unitTrustType != null)
                            model.Header.UnitTrustTypeName = unitTrustType.Text;
                        var unitTrustCompany = oldModel.CompanyList.SingleOrDefault(x => x.Value == model.Header.UnitTrustCompanyID.GetValueOrDefault().ToString());
                        if (unitTrustCompany != null)
                            model.Header.UnitTrustCompanyName = unitTrustCompany.Text;
                        var assetMgmtName = oldModel.AssetManagementCompanyList.SingleOrDefault(x => x.Value == model.Header.AssetMgmtID.GetValueOrDefault().ToString());
                        if (assetMgmtName != null)
                            model.Header.AssetMgmtName = assetMgmtName.Text;

                        var co = oldModel.ScreenData.Companies.SingleOrDefault(x => x.CompanyId == model.Header.UnitTrustCompanyID.GetValueOrDefault());
                        if (co != null)
                            model.Header.UnitTrustCompanyName = co.CompanyNameEn;


                        if (model.UpdateMode || oldModel.UpdateMode)
                        {
                            model.Header.ID = oldModel.Header.ID;
                            model.Header.ModifyBY = ServiceFactory.UserId;
                            model.Header.CreateBY = oldModel.Header.CreateBY;
                            model.Header.CreateDate = oldModel.Header.CreateDate;
                            model.Header.ModifyDate = oldModel.Header.ModifyDate;
                            var result = Service.UpdateUnitTrustHeader(model.Header);
                            oldModel.Header = result.Header;
                            oldModel.ScreenData.HeaderDTO = result;
                            oldModel.Transactions = result.Transactions;
                        }
                        else
                        {
                            model.Header.CreateBY = ServiceFactory.UserId;

                            //model.Header.RemainUnit = model.Header.

                            var result = Service.InsertUnitTrustHeader(model.Header);
                            oldModel.Header = result.Header;
                            oldModel.ScreenData.HeaderDTO = result;
                            oldModel.Transactions = result.Transactions;
                        }
                        oldModel.UpdateMode = true;
                        ViewBag.UpdateMode = true;
                        ViewBagUtil.SetCompletedInfo(ViewBag);
                    }
                    else
                    {
                        throw new Exception("Button save (BtnSave) is null.");
                    }
                }
                catch (Exception ex)
                {
                    //ModelState.AddModelError("", ex.Message);
                    ViewBagUtil.SetError(ViewBag, ex.Message, null);
                }
            }
            TempData["EditUnitTrustHeaderModel"] = oldModel;
            return View(oldModel);
        }
        #endregion

        #region Transaction -->Purchase

        public ActionResult AddPurchaseTransaction(int headerId)
        {
            EditUnitTrustPurchaseModel model = null;
            try
            {
                var data = Service.GetUnitTrustTransactionScreenData(headerId, null, "Purchase");
                model = EditUnitTrustPurchaseModel.BuildModel(data);
                TempData["EditUnitTrustPurchaseModel"] = model;
            }
            catch (Exception ex)
            {
                model = new EditUnitTrustPurchaseModel();
                //ModelState.AddModelError("", ex.Message);
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }
            return View("EditPurchaseTransaction", model);
        }

        public ActionResult EditPurchaseTransaction(int transactionId)
        {
            EditUnitTrustPurchaseModel model = null;
            try
            {
                var data = Service.GetUnitTrustTransactionScreenData(null, transactionId, "Purchase");
                model = EditUnitTrustPurchaseModel.BuildModel(data);
                model.UpdateMode = true;
                TempData["EditUnitTrustPurchaseModel"] = model;
            }
            catch (Exception ex)
            {
                model = new EditUnitTrustPurchaseModel();
                //ModelState.AddModelError("", ex.Message);
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }
            return View("EditPurchaseTransaction", model);
        }

        [HttpPost]
        public ActionResult EditPurchaseTransaction(EditUnitTrustPurchaseModel model)
        {
            var oldModel = (EditUnitTrustPurchaseModel)TempData["EditUnitTrustPurchaseModel"];
            if (ModelState.IsValid)
            {
                try
                {
                    if (!String.IsNullOrEmpty(model.SubmitBtn))
                    {
                        if (model.UpdateMode || oldModel.UpdateMode)
                        {
                            model.Transaction.ID = oldModel.Transaction.ID;
                            model.Transaction.ModifyBY = ServiceFactory.UserId;
                            model.Transaction.CreateBY = oldModel.Transaction.CreateBY;
                            model.Transaction.CreateDate = oldModel.Transaction.CreateDate;
                            model.Transaction.ModifyDate = oldModel.Transaction.ModifyDate;
                            oldModel.Transaction = Service.UpdateUnitTrustTransaction(model.Transaction);
                        }
                        else
                        {
                            model.Transaction.CreateBY = ServiceFactory.UserId;
                            oldModel.Transaction = Service.InsertUnitTrustTransaction(model.Transaction);
                        }
                        oldModel.UpdateMode = true;
                        ViewBagUtil.SetCompletedInfo(ViewBag);
                    }
                    else
                    {
                        throw new Exception("Button save (BtnSave) is null.");
                    }
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", ex.Message);
                    //ModelState.AddModelError("", ex.Message);
                    ViewBagUtil.SetError(ViewBag, ex.Message, null);
                }
            }
            TempData["EditUnitTrustPurchaseModel"] = oldModel;
            return View("EditPurchaseTransaction", oldModel);
        }
        #endregion

        #region Transaction -->Sale

        public ActionResult AddSaleTransaction(int headerId)
        {
            EditUnitTrustSaleModel model = null;
            try
            {
                var data = Service.GetUnitTrustTransactionScreenData(headerId, null, "Sale");
                model = EditUnitTrustSaleModel.BuildModel(data);
                TempData["EditUnitTrustSaleModel"] = model;
            }
            catch (Exception ex)
            {
                model = new EditUnitTrustSaleModel();
                //ModelState.AddModelError("", ex.Message);
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }
            return View("EditSaleTransaction", model);
        }

        public ActionResult EditSaleTransaction(int transactionId)
        {
            EditUnitTrustSaleModel model = null;
            try
            {
                var data = Service.GetUnitTrustTransactionScreenData(null, transactionId, "Sale");
                model = EditUnitTrustSaleModel.BuildModel(data);
                model.UpdateMode = true;
                TempData["EditUnitTrustSaleModel"] = model;
            }
            catch (Exception ex)
            {
                model = new EditUnitTrustSaleModel();
                //ModelState.AddModelError("", ex.Message);
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }
            return View("EditSaleTransaction", model);
        }

        [HttpPost]
        public ActionResult EditSaleTransaction(EditUnitTrustSaleModel model)
        {
            var oldModel = (EditUnitTrustSaleModel)TempData["EditUnitTrustSaleModel"];
            if (ModelState.IsValid)
            {
                try
                {
                    if (!String.IsNullOrEmpty(model.SubmitBtn))
                    {
                        if (model.UpdateMode || oldModel.UpdateMode)
                        {
                            model.Transaction.ID = oldModel.Transaction.ID;
                            model.Transaction.ModifyBY = ServiceFactory.UserId;
                            model.Transaction.CreateBY = oldModel.Transaction.CreateBY;
                            model.Transaction.CreateDate = oldModel.Transaction.CreateDate;
                            model.Transaction.ModifyDate = oldModel.Transaction.ModifyDate;
                            oldModel.Transaction = Service.UpdateUnitTrustTransaction(model.Transaction);
                        }
                        else
                        {
                            model.Transaction.CreateBY = ServiceFactory.UserId;
                            oldModel.Transaction = Service.InsertUnitTrustTransaction(model.Transaction);
                        }
                        oldModel.UpdateMode = true;
                        ViewBagUtil.SetCompletedInfo(ViewBag);
                    }
                    else
                    {
                        throw new Exception("Button save (BtnSave) is null.");
                    }
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", ex.Message);
                    //ModelState.AddModelError("", ex.Message);
                    ViewBagUtil.SetError(ViewBag, ex.Message, null);
                }
            }
            TempData["EditUnitTrustSaleModel"] = oldModel;
            return View("EditSaleTransaction", oldModel);
        }
        #endregion

        #region Transaction -->Guarantee

        public ActionResult AddGuaranteeTransaction(int headerId)
        {
            EditUnitTrustGuaranteeModel model = null;
            try
            {
                var data = Service.GetUnitTrustTransactionScreenData(headerId, null, "Guarantee");
                model = EditUnitTrustGuaranteeModel.BuildModel(data);
                TempData["EditUnitTrustGuaranteeModel"] = model;
            }
            catch (Exception ex)
            {
                model = new EditUnitTrustGuaranteeModel();
                //ModelState.AddModelError("", ex.Message);
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }
            return View("EditGuaranteeTransaction", model);
        }

        [HttpGet]
        public ActionResult EditGuaranteeTransaction(int transactionId)
        {
            EditUnitTrustGuaranteeModel model = null;
            try
            {
                var data = Service.GetUnitTrustTransactionScreenData(null, transactionId, "Guarantee");
                model = EditUnitTrustGuaranteeModel.BuildModel(data);
                model.UpdateMode = true;
                TempData["EditUnitTrustGuaranteeModel"] = model;
            }
            catch (Exception ex)
            {
                model = new EditUnitTrustGuaranteeModel();
                //ModelState.AddModelError("", ex.Message);
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }
            return View("EditGuaranteeTransaction", model);
        }

        [HttpPost]
        public ActionResult EditGuaranteeTransaction(EditUnitTrustGuaranteeModel model)
        {
            var oldModel = (EditUnitTrustGuaranteeModel)TempData["EditUnitTrustGuaranteeModel"];
            if (ModelState.IsValid)
            {
                try
                {
                    if (!String.IsNullOrEmpty(model.SubmitBtn))
                    {
                        if (model.UpdateMode || oldModel.UpdateMode)
                        {
                            model.Transaction.ID = oldModel.Transaction.ID;
                            model.Transaction.ModifyBY = ServiceFactory.UserId;
                            model.Transaction.CreateBY = oldModel.Transaction.CreateBY;
                            model.Transaction.CreateDate = oldModel.Transaction.CreateDate;
                            model.Transaction.ModifyDate = oldModel.Transaction.ModifyDate;
                            oldModel.Transaction = Service.UpdateUnitTrustTransaction(model.Transaction);
                        }
                        else
                        {
                            model.Transaction.CreateBY = ServiceFactory.UserId;
                            oldModel.Transaction = Service.InsertUnitTrustTransaction(model.Transaction);
                        }
                        oldModel.UpdateMode = true;
                        ViewBagUtil.SetCompletedInfo(ViewBag);
                    }
                    else
                    {
                        throw new Exception("Button save (BtnSave) is null.");
                    }
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", ex.Message);
                    //ModelState.AddModelError("", ex.Message);
                    ViewBagUtil.SetError(ViewBag, ex.Message, null);
                }
            }
            TempData["EditUnitTrustGuaranteeModel"] = oldModel;
            return View("EditGuaranteeTransaction", oldModel);
        }
        #endregion

        #region Transaction --> Privilege

        public ActionResult ManageUnitTrustPrivilege(int headerId)
        {
            ManageUnitTrustPrivilegeModel model = null;
            try
            {
                var data = Service.GetPrivilegeDataByHeaderId(headerId);
                model = ManageUnitTrustPrivilegeModel.BuildModel(data);
            }
            catch (Exception ex)
            {
                model = new ManageUnitTrustPrivilegeModel();
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }
            TempData["ManageUnitTrustPrivilegeModel"] = model;
            return View("ManageUnitTrustPrivilege", model);
        }

        public ActionResult AddUnitTrustPrivilege(int headerId)
        {
            EditUnitTrustPrivilegeModel model = null;
            try
            {
                var data = Service.GetUnitTrustPrivilegeScreenData(headerId, null);
                model = EditUnitTrustPrivilegeModel.BuildModel(data);
                TempData["EditUnitTrustPrivilegeModel"] = model;
            }
            catch (Exception ex)
            {
                model = new EditUnitTrustPrivilegeModel();
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }
            return View("EditUnitTrustPrivilege", model);
        }

        public ActionResult EditUnitTrustPrivilege(int privilegeId)
        {
            EditUnitTrustPrivilegeModel model = null;
            try
            {
                var data = Service.GetUnitTrustPrivilegeScreenData(null, privilegeId);
                model = EditUnitTrustPrivilegeModel.BuildModel(data);
                model.UpdateMode = true;
                TempData["EditUnitTrustPrivilegeModel"] = model;
            }
            catch (Exception ex)
            {
                model = new EditUnitTrustPrivilegeModel();
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }
            return View("EditUnitTrustPrivilege", model);
        }

        [HttpPost]
        public ActionResult EditUnitTrustPrivilege(EditUnitTrustPrivilegeModel model)
        {
            var oldModel = (EditUnitTrustPrivilegeModel)TempData["EditUnitTrustPrivilegeModel"];
            if (ModelState.IsValid)
            {
                try
                {
                    if (!String.IsNullOrEmpty(model.SubmitBtn))
                    {
                        var item = oldModel.TypeList.First(x => x.Value == model.Privilege.PrivilegeTypeID.GetValueOrDefault().ToString());
                        if (item != null)
                            model.Privilege.PrivilegeTypeName = item.Text;

                        if (model.UpdateMode || oldModel.UpdateMode)
                        {
                            model.Privilege.ID = oldModel.Privilege.ID;
                            model.Privilege.ModifyBY = ServiceFactory.UserId;
                            model.Privilege.CreateBY = oldModel.Privilege.CreateBY;
                            model.Privilege.CreateDate = oldModel.Privilege.CreateDate;
                            model.Privilege.ModifyDate = oldModel.Privilege.ModifyDate;
                            oldModel.Privilege = Service.UpdateUnitTrustPrivilege(model.Privilege);
                        }
                        else
                        {
                            model.Privilege.CreateBY = ServiceFactory.UserId;
                            oldModel.Privilege = Service.InsertUnitTrustPrivilege(model.Privilege);
                        }
                        oldModel.UpdateMode = true;
                        ViewBagUtil.SetCompletedInfo(ViewBag);
                    }
                    else
                    {
                        throw new Exception("Button save (BtnSave) is null.");
                    }
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", ex.Message);
                    ViewBagUtil.SetError(ViewBag, ex.Message, null);
                }
            }
            TempData["EditUnitTrustPrivilegeModel"] = oldModel;
            return View("EditUnitTrustPrivilege", oldModel);
        }


        #endregion


        #region Transaction --> Proportion สัดส่วนการลงทุน

        public ActionResult EditUnitTrustProportion(int headerId)
        {
            EditUnitTrustProportionModel model = null;
            UnitTrustProportionScreenData data = null;
            try
            {
                data = Service.GetUnitTrustProportionScreenData(headerId, null);
                model = EditUnitTrustProportionModel.BuildModel(data);
            }
            catch (Exception ex)
            {
                model = new EditUnitTrustProportionModel();
                ViewBagUtil.SetError(ViewBag, ex.Message, null);
            }
            //if (data == null || data.HeaderDTO == null || data.HeaderDTO.Header == null)
            //{
            //    ViewBag.ErrorMsg = "Please save a Header before.";
            //    return ViewBag;
            //}
            TempData["EditUnitTrustProportionModel"] = model;
            return View("EditUnitTrustProportion", model);
        }

        [HttpPost]
        public ActionResult EditUnitTrustProportion(EditUnitTrustProportionModel model)
        {
            var oldModel = (EditUnitTrustProportionModel)TempData["EditUnitTrustProportionModel"];
            if (ModelState.IsValid)
            {
                try
                {
                    if (!String.IsNullOrEmpty(model.SubmitBtn))
                    {
                        if (model.UpdateMode || oldModel.UpdateMode)
                        {
                            model.Proportion.ID = oldModel.Proportion.ID;
                            model.Proportion.ModifyBY = ServiceFactory.UserId;
                            model.Proportion.CreateBY = oldModel.Proportion.CreateBY;
                            model.Proportion.CreateDate = oldModel.Proportion.CreateDate;
                            model.Proportion.ModifyDate = oldModel.Proportion.ModifyDate;
                            oldModel.Proportion = Service.UpdateUnitTrustProportion(model.Proportion);
                        }
                        else
                        {
                            model.Proportion.CreateBY = ServiceFactory.UserId;
                            oldModel.Proportion = Service.InsertUnitTrustProportion(model.Proportion);
                        }
                        oldModel.UpdateMode = true;
                        ViewBagUtil.SetCompletedInfo(ViewBag);
                    }
                    else
                    {
                        throw new Exception("Button save (BtnSave) is null.");
                    }
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", ex.Message);
                    ViewBagUtil.SetError(ViewBag, ex.Message, null);
                }
            }
            TempData["EditUnitTrustProportionModel"] = oldModel;
            return View("EditUnitTrustProportion", oldModel);
        }


        #endregion


    }
}
